import { Extension } from "@tiptap/core";
import { upload } from '../utils/upload.ts';
import { marked } from 'marked'
import i18n from "../i18n/index.ts";
import Editor from './core.ts'
export interface OperationOptions {
    onSave?: () => void,
    onExport?: (type: String, e: Editor) => void,
    onShare?: () => void
}
declare module '@tiptap/core' {
    interface Commands<ReturnType> {
        operation: {
            save: () => ReturnType,
            import: () => ReturnType,
            export: (type: String) => ReturnType,
            share: () => ReturnType,
        }
    }
}

export const Operation = Extension.create<OperationOptions>({
    name: "operation",
    addCommands() {
        return {
            save: () => () => {
                if (this.options.onSave) {
                    this.options.onSave();
                }
                return false;
            },
            import: () => ({ editor }) => {
                const importSuccess = i18n.t(['import', 'success']);
                upload({ accept: 'application/json, text/*, text/markdown'}).then((res) => {
                    if (res.type === 'application/json') {
                        if (typeof res.data === 'string') {
                            const jsonData = JSON.parse(res.data);
                            editor.commands.setContent(jsonData, true);
                            (editor as Editor)?.message?.success(importSuccess)
                        }
                    } else if (res.type === 'text/html' || res.type === 'text/plain') {
                        editor.commands.setContent(res.data, true);
                        (editor as Editor)?.message?.success(importSuccess)
                    }
                    else if (res.type === 'text/markdown') {
                        const content = marked.parse(res.data as string);
                        editor.commands.setContent(content, true);
                        (editor as Editor)?.message?.success(importSuccess)
                    } else {
                        (editor as Editor)?.message?.error(i18n.t('noSupportFile'))
                    }
                }).catch((err) => {
                    (editor as Editor)?.message?.error(err)
                })
                return false;
            },
            export: (type) => ({ editor }) => {
                if (this.options.onExport) {
                    this.options.onExport(type, editor)
                }
                return false;
            },
            share: () => () => {
                if (this.options.onShare) {
                    this.options.onShare()
                }
                return false;
            },
        }
    }
})
